var datagrid; //定义全局变量datagrid
var editRow = undefined; //定义全局变量：当前编辑的行
var selectUserId = "";//人员编辑id
$(function () {
    //加载部门树
    queryDepartmentTree();
    //  alert(CONSTANT.DictionaryTypeDefConstants.HD_REASON);
    //加载数据字典下拉列表
    queryDictionaryList("accidentLevelId", CONSTANT.DictionaryTypeDefConstants.ACCIDENT_LEVEL);//事故等级
    queryDictionaryList("accidentTypeId", CONSTANT.DictionaryTypeDefConstants.ACCIDENT_TYPE);//事故类别

    /**
     * 保存按钮事件
     */
    $('#btn_save').on("click", function () {
        //var ret = $("#hdRegisterForm").form('validate');
        //表单验证
        if ($("#infoForm").form('validate')) {
            layer.confirm("确定保存？", {btn: ['确定', '取消']}, function () {
                var layerIndex = parent.layer.getFrameIndex(window.name); //获取窗口索引
                //序列化表单数据
                var data = $("#infoForm").serializeArray();
                $.ajax({
                    url: ROOT_PATH + '/accidentEvent/accident/addAccidentInfo.shtml',//提交地址
                    data: data,//将表单数据序列化
                    type: "POST",
                    dataType: "json",
                    success: function (result) {
                        if (result.success) {
                            layer.msg(result.message, {time: 1000, icon: 1}, function () {
                                WindowManager.closeLayer({
                                    returnValue: ""
                                });
                            });
                        } else {
                            layer.msg(result.message, {time: 1000, icon: 1}, function () {
                                //parent.layer.close(layerIndex);
                            });
                        }
                    }
                });
            });
        } else {
            layer.msg("请按规则填写信息!", {time: 1000, icon: 2});
        }

    });

    /**
     * 提交按钮事件
     */
    $('#btn_submit').on("click", function () {
        //var ret = $("#hdRegisterForm").form('validate');
        //表单验证
        if ($("#infoForm").form('validate')) {
            layer.confirm("确定保存并提交审批？", {btn: ['确定', '取消']}, function () {
                var layerIndex = parent.layer.getFrameIndex(window.name); //获取窗口索引
                //序列化表单数据
                var data = $("#infoForm").serializeArray();
                /***
                 * 选择处理人
                 */
                WindowManager.openLayer({
                    type: 2,
                    title: '选择下一环节处理人',
                    area: ['370px', '180px'],
                    content: ROOT_PATH + '/workflow/flowManagement/toFlowNextUserSelectPage.shtml',
                    data: {id: 'ff', name: '我是名称'},
                    callBack: function (result) {//窗口关闭后的回调函数
                        //得到选择的人员
                        if (result == null || result === "") {
                            layer.alert("请选择处理人!");
                            return false;
                        }
                        data.push({name: 'nextUserId', value: result});
                        $.ajax({
                            url: ROOT_PATH + '/accidentEvent/accident/addAndSubmit.shtml',//提交地址
                            data: data,//将表单数据序列化
                            type: "POST",
                            dataType: "json",
                            success: function (result) {
                                if (result.success) {
                                    layer.msg(result.message, {time: 1000, icon: 1}, function () {
                                        WindowManager.closeLayer({
                                            returnValue: ""
                                        });
                                    });
                                } else {
                                    layer.msg(result.message, {time: 1000, icon: 1}, function () {
                                        //parent.layer.close(layerIndex);
                                    });
                                }
                            }
                        });

                    }
                });


            });
        } else {
            layer.msg("请按规则填写信息!", {time: 1000, icon: 2});
        }

    });
    /**
     * 绑定人员选择事件
     */

    $("#reportUser").textbox({
        iconWidth: 15,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                selectUserId = "reportUser";
                add_contractorInfo_func();
            }
        }]
    });
    $("#safetyDeptDutyUser").textbox({
        iconWidth: 15,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                selectUserId = "safetyDeptDutyUser";
                add_contractorInfo_func();
            }
        }]
    });
    $("#chargeLeader").textbox({
        iconWidth: 15,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                selectUserId = "chargeLeader";
                add_contractorInfo_func();
            }
        }]
    });
    /**
     * 选择风险区域
     */
    $("#site").textbox({
        iconWidth: 15,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                selectUserId = "site";
                add_riskRegionInfo_func();
            }
        }]
    });
    /**
     * 绑定作业项目选择事件
     */
    $("#project").textbox({
        iconWidth: 15,
        height: 30,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                //selectUserId ="recogniseUsers";
                add_jobProject_func();
            }
        }]
    });
    /**
     * 选择承包商
     */
    $("#contractor").textbox({
        iconWidth: 15,
        height: 30,
        icons: [{
            iconCls: 'icon-add',
            handler: function (e) {
                WindowManager.openLayer({
                    type: 2,
                    title: '选择承包商',
                    area: ['700px', '400px'],
                    content: ROOT_PATH + '/contractor/contractorAudit/auditedList.shtml',
                    callBack: function (data) {
                        console.log(data);
                        $("#contractorId").val(data[0].id);
                        $("#contractor").textbox("setValue", data[0].contractorName);
                    }
                });
            }
        }]
    });
    /**
     * 是否承包商切换
     */
    $("#isContractor").combobox({
        onSelect: function (record) {
            var val = record.value;
            if (val == 1) {
                $("#contractorDiv").show();
                $("#contractor").textbox("enableValidation");
            } else {
                $("#contractorDiv").hide();
                $("#contractor").textbox("clear");
                $("#contractor").textbox("disableValidation");
                $("#contractorId").val('');
            }
        }
        /*,
         onChange:function(newVal,oldVal){
         if(newVal!=oldVal){
         if(newVal==1){
         $("#contractorDiv").show();
         $("#contractor").textbox("enableValidation");
         }else{
         $("#contractorDiv").hide();
         $("#contractor").textbox("clear");
         $("#contractor").textbox("disableValidation");
         $("#contractorId").val('');
         }
         }
         }*/
    });
    /**
     * 是否选择工厂模式切换
     */
    $("#isFactoryModel").combobox({
        onSelect: function (record) {
            var val = record.value;
            if (val == 1) {
                $("#siteNameDiv").hide();
                $("#siteName").textbox("clear");
                $("#siteName").textbox("disableValidation");
                $("#siteIdDiv").show();
                $("#site").textbox("enableValidation");
            } else {
                $("#siteIdDiv").hide();
                $("#siteId").val('');
                $("#site").textbox("clear");
                $("#site").textbox("disableValidation");
                $("#siteNameDiv").show();
                $("#siteName").textbox("enableValidation");
            }
        }
        /*,onChange:function(newVal,oldVal){
         if(newVal!=oldVal){
         if(newVal==1){
         $("#siteNameDiv").hide();
         $("#siteName").textbox("clear");
         $("#siteName").textbox("disableValidation");
         $("#siteIdDiv").show();
         $("#site").textbox("enableValidation");
         }else{
         $("#siteIdDiv").hide();
         $("#siteId").val('');
         $("#site").textbox("clear");
         $("#site").textbox("disableValidation");
         $("#siteNameDiv").show();
         $("#siteName").textbox("enableValidation");
         }
         }
         }*/
    });

});
/**
 * 定义表单验证
 */
$.extend($.fn.validatebox.defaults.rules, {
    minLength: {
        validator: function (value, param) {
            return value.length >= param[0];
        },
        message: '最小长度'
    },
    intOrFloat: {// 验证整数或小数
        validator: function (value) {
            // alert(/^\d+(\.\d+)?$/i.test(value));
            return /^\d+(\.\d+)?$/i.test(value);
        },
        message: '请输入数字，并确保格式正确'
    },
    validSelect: {//验证为空字符串
        validator: function (value) {
            //alert(value!="请选择");
            return value != "请选择" && value != '';
        },
        message: '请选择'
    }

});
/**
 * 查询部门树方法
 */
function queryDepartmentTree() {
    $.ajax({
        url: ROOT_PATH + '/permission/department/getDepartmentTree.shtml',//提交地址
        data: {parentId: 0},//将表单数据序列化
        type: "POST",
        dataType: "json",
        success: function (result) {
            $('#dept').combotree(
                {
                    data: result,
                    loadFilter: function (data) {
                        var newData = new Array();
                        newData.push({id: "", text: '请选择'});
                        newData.push(data[0]);
                        return newData;
                    }
                }
            );
            //事故发生单位
            $("#happenDeptId").combotree({
                data: result,
                loadFilter: function (data) {
                    var newData = new Array();
                    newData.push({id: "", text: '请选择'});
                    newData.push(data[0]);
                    return newData;
                }
            });
            //报告单位
            $("#reportDeptId").combotree({
                data: result,
                loadFilter: function (data) {
                    var newData = new Array();
                    newData.push({id: "", text: '请选择'});
                    newData.push(data[0]);
                    return newData;
                }
            });
            //主管单位
            $("#competentDeptId").combotree({
                data: result,
                loadFilter: function (data) {
                    var newData = new Array();
                    newData.push({id: "", text: '请选择'});
                    newData.push(data[0]);
                    return newData;
                }
            });
        }
    });
}
/**
 * 人员信息选择
 */
var add_contractorInfo_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择人员信息',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/permission/user/simpleList.shtml?isMulti=0',
        callBack: function (data) {//窗口关闭后的回调函数
            //$('#listGrid').datagrid("reload");
            if (selectUserId == "" || selectUserId == null) {
                var dutyUserED = datagrid.datagrid('getEditor', {index: editRow, field: 'dutyUserName'});
                var dutyUserIdED = datagrid.datagrid('getEditor', {index: editRow, field: 'dutyUserId'});
                $(dutyUserED.target).textbox("setValue", data[0].realName)
                $(dutyUserIdED.target).textbox("setValue", data[0].id)
            } else {//给正常文本框赋值
                //$("#"+selectUserId+"Id").textbox('setValue',data[0].id);
                $("#" + selectUserId).textbox('setValue', data[0].realName);
                $("#" + selectUserId + "Id").val(data[0].id);
                selectUserId = "";
            }
        }
    });
};
/**
 * 选择风险区域的方法
 */
var add_riskRegionInfo_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择风险区域',
        area: ['1150px', '70%'],
        content: ROOT_PATH + '/risk/region/simpleList.shtml',
        callBack: function (data) {//窗口关闭后的回调函数
            $("#" + selectUserId).textbox('setValue', data.name);
            //$("#"+selectUserId+"Id").textbox('setText',data.name);
            $("#" + selectUserId + "Id").val(data.id);
            selectUserId = "";

        }
    });
}
/**
 * 选择作业项目
 */
var add_jobProject_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择项目',
        area: ['800px', '300px'],
        content: ROOT_PATH + '/threeSimultaneities/projectInfo/projectQueryList.shtml',
        callBack: function (data) {
            //alert();
            $("#projectId").val(data[0].id);
            $("#project").textbox("setValue", data[0].name);
            //("#jobProject").textbox("setText",data[0].name);
        }
    });
}

/**
 * 查询数据字典列表的方法
 * @param id
 * @param code
 */
function queryDictionaryList(id, code) {
    $.ajax({
        url: ROOT_PATH + '/permission/dictionary/queryDictionaryByDictionaryTypeCode.shtml',//提交地址
        data: {code: code},//将表单数据序列化
        type: "POST",
        dataType: "json",
        success: function (result) {
            $('#' + id).combobox(
                {
                    data: result,
                    valueField: 'id',
                    textField: 'text',
                    loadFilter: function (data) {
                        var newData = new Array();
                        newData.push({id: "", text: '请选择'});
                        for (var i = 0; i < data.length; i++) {
                            newData.push(data[i])
                        }
                        return newData;
                    }
                }
            );

        }
    });
}
/**
 * 设置年度下拉列表
 * @param id
 * @param code
 */
function queryYearthList(id) {
    var date = new Date();
    var year = date.getFullYear();
    var yearthData = new Array();
    yearthData.push({id: "", text: "请选择"});
    for (var i = 0; i < 6; i++) {
        var y = {id: year - i, text: (year - i) + '年'}
        yearthData.push(y);
    }
    $('#' + id).combobox(
        {
            data: yearthData,
            valueField: 'id',
            textField: 'text'
        }
    );
}
/**
 * 选择风险信息弹出框方法
 */
var add_riskLevelInfo_func = function () {
    WindowManager.openLayer({
        type: 2,
        title: '选择风险矩阵信息',
        area: ['60%', '70%'],
        content: ROOT_PATH + '/risk/matrix/toMatrixPage.shtml',
        callBack: function (data) {//窗口关闭后的回调函数
            $("#riskAssessMax").textbox("setValue", data.riskMax);
            $("#riskAssessPeople").textbox("setValue", data.riskPeople);
            $("#riskAssessMoney").textbox("setValue", data.riskMoney);
            $("#riskAssessEnvironment").textbox("setValue", data.riskEnvironment);
            $("#riskAssessPrestige").textbox("setValue", data.riskPrestige);
            $("#riskAssessUserId").textbox("setValue", loginUserId);
            $("#riskAssessUserId").textbox("setText", loginUserName);
        }
    });
};




